<template>
  <div class="knowledge-base-list-container">
    <AxiomGroup v-if="knowledgeBases.length > 0" wrap gap="large">
      <AxiomCard
        v-for="kb in knowledgeBases"
        :key="kb.id"
        borderedFooter
        width="320px"
        hoverable
      >
        <template #header>
          <AxiomGroup justify="space-between" align="center" class="w-100">
            <AxiomText weight="bold" truncate>{{ kb.name }}</AxiomText>
            <AxiomDropdown @command="handleCommand($event, kb)" trigger="click">
              <AxiomButton icon="more-filled" text circle />
              <template #dropdown>
                <AxiomDropdownMenu>
                  <AxiomDropdownItem command="edit" icon="edit">编辑</AxiomDropdownItem>
                  <AxiomDropdownItem command="delete" icon="delete" divided>删除</AxiomDropdownItem>
                </AxiomDropdownMenu>
              </template>
            </AxiomDropdown>
          </AxiomGroup>
        </template>
        
        <div class="h-42px">
            <AxiomText type="secondary" size="small" :truncate="2">{{ kb.description || '暂无描述' }}</AxiomText>
        </div>

        <template #footer>
          <AxiomGroup justify="space-between" align="center" class="w-100">
            <AxiomText type="secondary" size="small">查询模型: {{ kb.query_embedding_profile || 'N/A' }}</AxiomText>
            <AxiomButton type="primary" text @click="goToDocuments(kb)">进入文件</AxiomButton>
          </AxiomGroup>
        </template>
      </AxiomCard>
    </AxiomGroup>
    
    <AxiomEmpty v-else-if="!loading" description="暂无知识库，请点击页面右上角的“新建知识库”创建一个。" />

    <div ref="sentinel" style="height: 10px;"></div>
    <AxiomLoading v-if="loading" text="加载中..." />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, inject, defineEmits, defineExpose } from 'vue';
import { useRouter } from 'vue-router';
import {
  AxiomGroup,
  AxiomCard,
  AxiomText,
  AxiomEmpty,
  AxiomLoading,
  AxiomDropdown,
  AxiomDropdownMenu,
  AxiomDropdownItem,
  AxiomButton,
} from 'axiom-view';
import { knowledgeBaseApi } from '@/api/knowledge/knowledgeBase.js';

const emit = defineEmits(['edit-knowledge-base']);
const { notification, useConfirm } = inject('axiom-utils');
const { show: showConfirm } = useConfirm;
const router = useRouter();

const knowledgeBases = ref([]);
const page = ref(1);
const pageSize = ref(20);
const total = ref(0);
const loading = ref(false);
const sentinel = ref(null);

const hasMore = () => knowledgeBases.value.length < total.value;

function goToDocuments(kb) {
  router.push({ name: 'KnowledgeBaseDocuments', params: { kb_id: kb.id } });
}

async function fetchKnowledgeBases(isLoadMore = false) {
  if (loading.value || (isLoadMore && !hasMore())) return;

  if (!isLoadMore) {
    page.value = 1;
    knowledgeBases.value = [];
    total.value = 0;
  }
  
  loading.value = true;
  try {
    const res = await knowledgeBaseApi.getList({ page: page.value, page_size: pageSize.value });
    if (res.data && res.data.items) {
      knowledgeBases.value.push(...res.data.items);
      total.value = res.data.total;
      page.value++;
    } else {
       total.value = knowledgeBases.value.length;
    }
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
}

async function handleDeleteKnowledgeBase(kb) {
  await showConfirm({
    title: '确认删除',
    content: `您确定要删除知识库【${kb.name}】吗？`,
    type: 'error',
    onConfirm: async () => {
      await knowledgeBaseApi.delete(kb.id);
      notification.success({ title: '成功', message: '删除成功' });
      fetchKnowledgeBases(false);
    }
  });
}

function handleCommand(command, kb) {
    switch (command) {
        case 'edit':
            emit('edit-knowledge-base', kb);
            break;
        case 'delete':
            handleDeleteKnowledgeBase(kb);
            break;
    }
}

onMounted(() => {
  const observer = new IntersectionObserver(([entry]) => {
    if (entry.isIntersecting && hasMore()) {
      fetchKnowledgeBases(true);
    }
  }, {
    rootMargin: '0px 0px 100px 0px'
  });

  if (sentinel.value) {
    observer.observe(sentinel.value);
  }

  fetchKnowledgeBases(false);

  onUnmounted(() => {
    if (sentinel.value) {
      observer.unobserve(sentinel.value);
    }
  });
});

defineExpose({
  fetchKnowledgeBases: () => fetchKnowledgeBases(false),
});
</script> 